<template>
	<view class="chat">
    <!-- 顶部标题 -->
 
		<scroll-view  :style="{height: `${windowHeight-inputHeight - 180}rpx`}"
		id="scrollview"
		scroll-y="true" 
		:scroll-top="scrollTop"
		class="scroll-view"
		>
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.userContent != ''" >
						<!-- 文字内容 -->
						<view class="content right">
						
						<rich-text
							:nodes="item.userContent"
							class="ai-response"
						/>
						</view>
						<!-- 头像 -->
						<image class="avatar" :src="item.image">
						</image>
					</view>
					<!-- 机器人发的消息 -->
				<view class="item Ai" v-if="item.botContent || item.isLoading">
										<image 
											class="avatar" 
											:src="item.isLoading ? '/static/loading-avatar.png' : item.image"
										></image>
										<view class="content left">
											<rich-text 
												v-if="!item.isLoading && item.botContent"
												:nodes="item.botContent"
												class="ai-response"
											/>
											<view v-if="item.isLoading" class="loading-wrapper">
												<text>{{item.botContent}}</text>
												<view class="loading-circle"></view>
											</view>
										</view>
									</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight }rpx`}">
        <view class="uni-textarea">
          <textarea v-model="chatMsg"
		  :disabled="isWaiting"
            maxlength="300"
            confirm-type="send"
            @confirm="handleSend"
            placeholder="快来聊天吧~"
            :show-confirm-bar="false"
            :adjust-position="false"
            @linechange="sendHeight"
            @focus="focus" @blur="blur"
           auto-height
		    class="send-input"></textarea>
        </view >
			<button @click="handleSend"  :disabled="isWaiting" class="send-btn" 
style="background-image: url(/static/send.png);
background-repeat:no-repeat ;

background-size:contain; border: 0;
background-color: #1928dae0">
				
  </button>
  <!-- 文件上传按钮 -->
  <button @click="inputDialogToggle"   class="send-btn"
  style="background-image: url(/static/up.png);
  background-repeat:no-repeat ;
  background-size:contain; border: 0;
  background-color: transparent;">
  				
               </button>
		           <view>
					<!-- 输入框示例 -->
					<uni-popup ref="inputDialog" type="dialog">
						<uni-popup-dialog ref="inputClose"  mode="input" title="输入内容" value="对话框预置提示内容!"
							placeholder="请输入内容" @confirm="dialogInputConfirm">
							<view class="example-body">
											<uni-file-picker limit="1" title="最多选择1张图片" @select="uploadto"></uni-file-picker>
										</view>
							</uni-popup-dialog>
							
							
					</uni-popup>
				  </view>
				
			</view>
		</view>
	</view>
</template>
<script>
	
	export default{
		data() {
			return {
				 isWaiting: false, 
				 tempFilePaths: undefined,
				//键盘高度
				keyboardHeight:0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				userId:'',
				//发送的消息
				chatMsg:"",
				msgList:[
					{
					    botContent: "你好我是医疗助手有什么可以帮助你的吗？",
					    userContent: "",
                        image:"/static/logo.png",
						 isLoading: false  // 新增每个消息的独立状态
					},
				
				]	
			}
		},
		updated(){
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		
		computed: {
			windowHeight() {
			    return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight(){
				return this.bottomHeight+this.keyboardHeight
			}
		},
		onLoad(){
        uni.onKeyboardHeightChange(res => {
				
				this.keyboardHeight = this.rpxTopx(res.height)
				if(this.keyboardHeight<0)this.keyboardHeight = 0;
			})
		},
		onUnload(){
			// uni.offKeyboardHeightChange()
		},
		methods: {


       sendtoai(data) {
       return new Promise((resolve, reject) => {
        uni.request({
        url: 'http://localhost:8080/springbootb6962qd8/ai/chat',
        method: 'POST',
        data: { 'userMessage': data },
        header: { 'Content-Type': 'application/json; charset=UTF-8' },
        success: (res) => {
          const lastIndex = this.msgList.length - 1;
                     this.msgList[lastIndex] = {
					   userContent: "",
                       botContent: res.data.chatMessage,
                       image: "/static/logo.png",
                       isLoading: false  // 关闭加载状态
                     };
					  this.isWaiting=false
                     this.$forceUpdate();
                     resolve();
					
        },
        fail: (err) => {
          const lastIndex = this.msgList.length - 1;
                      this.msgList[lastIndex].isLoading = false;
					   this.isWaiting=false
                      reject(err);
					 
        }
      });
    });
  },
           goback() {
           uni.switchTab({
          url: "/pages/tutorship/tutorship"
        })
        },
			focus(){
				this.scrollToBottom()
			},
			blur(){
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px){
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = ( 750 / deviceWidth ) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight(){
				setTimeout(()=>{
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res =>{
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				},10)
			},
			// 滚动至聊天底部
			scrollToBottom(e){
				setTimeout(()=>{
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) =>{
						if(res[1].height > res[0].height){
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				},15)
			},
			// 发送消息
	     async handleSend() {
		  if(this.isWaiting){
			  return
		  }
	      if (!this.chatMsg.trim()) {
	        this.$modal.showToast('不能发送空白消息');
	        return;
	      }
	
	      try {
	        // 添加用户消息
	        this.msgList.push({
	          botContent: "",
	          userContent: this.chatMsg,
	          image: "/static/userhead.jpg",
	          isLoading: false
	        });
			 this.isWaiting=true
	        
	        // 添加正在加载的助手消息
	        this.msgList.push({
	          botContent: "查询中",
			  userContent: '',
	          image: "/static/logo.png",
	          isLoading: true  // 标记为加载状态
	        });
	
	        await this.sendtoai(this.chatMsg);
	        this.chatMsg = '';
	        this.scrollToBottom();
	      } catch (error) {
	        // 处理错误时更新最后一条状态
	        if(this.msgList.length > 0) {
	          this.msgList[this.msgList.length - 1].isLoading = false;
	        }
	        uni.showToast({ title: '请求失败', icon: 'none' });
	      }
	    },
		       uploadto(e) {
						this.tempFilePaths = e.tempFilePaths;//e是获取的图片源
					
					},

		
		
		
                 inputDialogToggle() {
     				this.$refs.inputDialog.open()
     			},
     			 dialogClose() {
     				
     			},
     			dialogInputConfirm(val) {
					this.msgList.push({
					  botContent: "分析中",
					  userContent: '',
					  image: "/static/logo.png",
					  isLoading: true  // 标记为加载状态
					});
					this.isWaiting=true	
					if(this.tempFilePaths){
						uni.uploadFile({
							
							url: 'http://localhost:8080/springbootb6962qd8/ai/upload', //上传图片的后端接口
							filePath: this.tempFilePaths[0],
							name: 'file',
							success: res => {
								
								
						   	
							let tep=res.data
							let result=JSON.parse(tep)
						
								const lastIndex = this.msgList.length - 1;
								this.msgList[lastIndex]={
								  botContent: "",
								  userContent: result.imgflie,
								  image: "/static/userhead.jpg",
								  isLoading: false  // 标记为加载状态
								};
								this.msgList.push({
									botContent: result.chatMessage,
									userContent: '',
									image: "/static/logo.png",
									isLoading: false  // 标记为加载状态
								})
								this.isWaiting=false
									this.tempFilePaths=undefined
							},fail() {
								const lastIndex = this.msgList.length - 1;
								this.msgList[lastIndex]={
								  botContent: "您的网络似乎遇到点问题，请稍后再试！",
								  userContent: '',
								  image: "/static/logo.png",
								  isLoading: false  // 标记为加载状态
								};
								this.isWaiting=false	
							}
						})
					}else{
						  const lastIndex = this.msgList.length - 1;
						this.msgList[lastIndex]={
						  botContent: "您未上传任何图片，请选择图片后点击确定",
						  userContent: '',
						  image: "/static/logo.png",
						  isLoading: false  // 标记为加载状态
						};
						this.isWaiting=false	
					}
				
     				uni.showLoading({
     					title: '3秒后会关闭'
     				})
     
     				setTimeout(() => {
     					uni.hideLoading()
     					this.value = val
     					// 关闭窗口后，恢复默认内容
     					this.$refs.inputDialog.close()
     				}, 3000)
     			},
		}
	}
</script>
<style lang="scss" scoped>
	
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;
	
	view,button,text,input,textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}
	.send-input{
		
		 
		
	}
	.send{
		width: 100%;
	}
	.ai-response {
	  img {
	    max-width: 100rpx;
	  }
	  table {
	    border-collapse: collapse;
	  }
	  /* 其他HTML内容样式适配 */
	}
 .example-body {
 		padding: 10px;
 		padding-top: 0;
 	}
	/* 聊天消息 */
	.chat {
		
     .topTabbar {
          width: 100%;
          height: 90rpx;
          line-height: 90rpx;
          display: flex;
          margin-top: 80rpx;
          justify-content: space-between;
      
          .icon {
            margin-left: 20rpx;
          }
      
          .text {
            margin: auto;
            font-size: 16px;
            font-weight: 700;
          }
      
          .button {
            width: 10%;
            margin: auto 20rpx auto 0rpx;
          }
        }
		.scroll-view {
			::-webkit-scrollbar {
					    display: none;
					    width: 0 !important;
					    height: 0 !important;
					    -webkit-appearance: none;
					    background: transparent;
					    color: transparent;
					  }
			
			// background-color: orange;
			background-color: #F6F6F6;
			
			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;
				
				.self {
					justify-content: flex-end;
				}
				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;
 
					.right {
						background-color: $chatContentbgc;
					}
					.left {
						background-color: #FFFFFF;
					}
                    // 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}
 
					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}
 
					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						// line-height: 42rpx;
					}
 
					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 50rpx;
						overflow: hidden;
						
						image {
							align-self: center;
						}
 
					}
				}
			}
		}
 
		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 100rpx;
			background-color: #F6F6F6;
			transition: all 0.1s ease;
			
			.send-msg {
				 display: flex;
				// align-items: center;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: transparent;
				transition: all 0.1s ease;
			}
 
			.uni-textarea {
				padding-bottom: 20rpx;  
				textarea {
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #f1f1f1;
					border-radius: 40rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 74rpx;
					padding: 5rpx 8rpx;
          text-indent: 30rpx;
				}
			}
            
			.send-btn {
				
				display: flex;
				align-items: center;
				justify-content: center;
				margin-top: 3px;
				margin-left: 5px;
				width: 120rpx;
				height: 75rpx;
				// background: transparent;
			
				//border-radius: 50rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}
	}
	.loading-wrapper {
	  display: flex;
	  align-items: center;
	  gap: 10rpx;
	  color: #666;
	
	  .loading-circle {
	    width: 30rpx;
	    height: 30rpx;
	    border: 4rpx solid #ddd;
	    border-top-color: #007AFF;
	    border-radius: 50%;
	    animation: rotate 1s linear infinite;
	  }
	}
	
	@keyframes rotate {
	  0% { transform: rotate(0deg); }
	  100% { transform: rotate(360deg); }
	}
	
	.send-btn[disabled],
	textarea[disabled] {
	  opacity: 0.6;
	  filter: grayscale(1);
	}
</style>